package efrei.ngo.util;
import java.util.ArrayList;

import efrei.ngo.entity.MsgPiece;
import efrei.ngo.servlet.LoginVldtServlet;
import nl.justobjects.pushlet.core.Event;
import nl.justobjects.pushlet.core.EventPullSource;

public class CometPull {
	static public class CometRatePull extends EventPullSource{
		static int count=0;

        @Override
        protected long getSleepTime() {
            return 3000L; //this set recycle time
        }

        @Override
        protected Event pullEvent() {
        	//System.out.println(count+++".\tInto pull Event");
        	//int pTo=LoginVldtServlet.p_id;
        	
            /*Event event = Event.createDataEvent("/chat"); //create a service
            event.setField("action","send"); //send to client
            event.setField("nick","pushlet");
            event.setField("msg","Hello world");
            return event;
            */
        	DatabaseAccess.connectToDB();
        	ArrayList<MsgPiece> list=DatabaseAccess.dbCheckNewIM();
        	MsgPiece msgT;
        	
        	if(list.size()==0){
        		//DatabaseAccess.endConnectionToDB();
        		return null;
        	}else{
        		Event event =Event.createDataEvent("/chat");
        		for(int i=0,len=list.size();i<len;i++){
        			msgT=list.get(i);
        			event.setField("M"+i+"IDF",msgT.getpFrom());
        			event.setField("M"+i+"MSG",msgT.getContent());
        			event.setField("M"+i+"Time",msgT.getsTime().toString());
        			event.setField("M"+i+"To", msgT.getpTo());
        			event.setField("M"+i+"From", efrei.ngo.util.DatabaseAccess.dbGetNameViaID(msgT.getpFrom()));
        		}
            	//DatabaseAccess.endConnectionToDB();
            	return event;
        	} 
        }
        
        private String genHTML(MsgPiece oneP){
        	return oneP.getpFrom()+"\t";
        }
       
    }
}
